package com.heima.datasync.service.impl;


import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.datasync.vo.SearchArticleVO;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lo
 * @date 2021/10/9
 */
@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {
    public static final String ARTICLE_INDEX_NAME = "app_info_article";

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    EsService<SearchArticleVO> esService;

    /**
     * 批量插入es输入数据
     *
     * @return
     */
    @Override
    public ResponseResult dataInit() {
        //1.获取所有文章数据
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        if (CollectionUtils.isEmpty(allArticles)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"没有文章数据");
        }
        //2.遍历集合
        List<SearchArticleVO> list = new ArrayList<>();
        allArticles.forEach(article->{
            SearchArticleVO searchArticleVO = new SearchArticleVO();
            //封装es类
            BeanUtils.copyProperties(article,searchArticleVO);
            searchArticleVO.setLayout(article.getLayout().intValue());
            list.add(searchArticleVO);
        });
        //3.批量导入数据
        esService.saveBatch(list, ARTICLE_INDEX_NAME);

        return ResponseResult.okResult();
    }
}
